﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace Nereus
{
    using Power;
    public class NProperty
    {
        public string Name
        {
            get; set;
        }

        public string Type
        {
            get; set;
        }

        public string Description
        {
            get; set;
        }

        public List<NProperty> SubProperties
        {
            get; set;
        }

        public static List<NProperty> BuildNProperties(Type mainPropertyType)
        {
            if (mainPropertyType == null)
            {
                return new List<NProperty>();
            }
            var nActionProperties = mainPropertyType.GetProperties();
            var nProperties = new List<NProperty>();
            foreach (var property in nActionProperties)
            {
                var nPropertyAttribute = property.GetCustomAttribute<NPropertyAttribute>();

                var nProperty = new NProperty()
                {
                    Name = property.Name,
                    Type = property.PropertyType.Name,
                };
                if (nPropertyAttribute != null)
                {
                    string enumDescription = string.Empty;
                    if (nPropertyAttribute.EnumType != null)
                    {
                        var names = nPropertyAttribute.EnumType.GetEnumNames();
                        var values = new List<int>();
                        foreach (var item in nPropertyAttribute.EnumType.GetFields(BindingFlags.Static | BindingFlags.Public))
                        {
                            values.Add(Convert.ToInt32(item.GetValue(null)));
                        }
                        for (var i = 0; i < names.Length; i++)
                        {
                            enumDescription += names[i] + "-" + values[i].ToString() + ",";
                        }
                    }
                    nProperty.Description = nPropertyAttribute.Description + enumDescription.TrimEnd(',');
                }

                if (property.PropertyType.IsGenericType)
                {
                    nProperty.SubProperties = new List<NProperty>();
                    nProperty.SubProperties.AddRange(BuildNProperties(property.PropertyType.GetGenericArguments()[0]));
                }
                nProperties.Add(nProperty);
            }
            return nProperties;
        }
    }


    public class NPropertyAttribute : Attribute
    {
        public string Description
        {
            get; set;
        }

        public Type EnumType
        {
            get; set;
        }

        public NPropertyAttribute(string description)
        {
            Description = description;
        }

        public NPropertyAttribute(Type enumType)
        {
            EnumType = enumType;
        }
    }
}
